package com.yinshu.teleshield.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.yinshu.teleshield.config.web.DateArgumentResolver;
import com.yinshu.teleshield.config.web.LocalDateTimeArgumentResolver;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@EnableWebMvc
@AutoConfiguration
public class WebAutoConfiguration implements WebMvcConfigurer {


    /**
     * 参数解析
     *
     * @param argumentResolvers 参数解析器
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new DateArgumentResolver());
        argumentResolvers.add(new LocalDateTimeArgumentResolver());
    }

    /**
     * description:LocalDateTime转换器，用于转换RequestParam和PathVariable参数
     * 接收毫秒级时间戳字符串——>LocalDateTime
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                //毫秒级时间戳转LocalDateTime
                if (StrUtil.isNumeric(source)) {
                    long timestamp = Long.parseLong(source);
                    return DateUtil.toLocalDateTime(new Date(timestamp));
                }
                return DateUtil.toLocalDateTime(DateUtil.parse(source));
            }
        };
    }

    /**
     * description:java.util.Date转换器
     * 接收毫秒级时间戳字符串——>Date
     */
    @Bean
    public Converter<String, Date> dateConverter() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                if (StrUtil.isNumeric(source)) {
                    long timestamp = Long.parseLong(source);
                    return new Date(timestamp);
                }
                return DateUtil.parse(source);
            }
        };
    }

}
